import React, { useEffect, useState } from "react";
import axios from "axios";
import { Button, Input } from "antd";
import reactIcon from "./assets/react.svg";
import head from "./assets/head.jpg";
import "./App.less";

const APIKey = "";
const SecretKey = "";

type TMsg = {
  role: string; //角色
  content: string; //内容
};
function App() {
  const [tokenInfo, setTokenInfo] = useState<{
    access_token: string;
  } | null>(null); //登录信息

  const [sendValue, setSendValue] = useState(""); //发送的内容
  const [msgList, setMsgList] = useState<TMsg[]>([]); //消息列表

  //获取登录凭证
  const getAccessToken = () => {
    //这里需要配置跨域，否则会出现无法加载相应数据的情况
    axios({
      method: "post",
      url: "/api/oauth/2.0/token",
      params: {
        grant_type: "client_credentials",
        client_id: APIKey, //在应用里
        client_secret: SecretKey, //在应用里
      },
    })
      .then(function (response) {
        console.log(response, "response");
        const { data } = response;
        setTokenInfo(data);
      })
      .catch(function (error) {
        console.error(error, "获取登录凭证报错了");
        alert("大概率要么是没配置跨域，要么是入参给错了，检查下哦");
      });
  };

  /**
   * 发送消息给ai
   */
  const sendInfoChat = (msg: TMsg) => {
    axios({
      method: "post",
      url: "/api/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-128k",
      headers: {
        "Content-Type": "application/json",
      },
      data: {
        messages: [msg],
      },
      params: {
        access_token: tokenInfo?.access_token,
      },
    })
      .then(function (response) {
        const { data } = response;
        const { result } = data;
        if (result) {
          setMsgList((msg) => {
            msg[msg.length - 1].content = result;
            return [...msg];
          });
        } else {
          setMsgList((msg) => {
            msg[msg.length - 1].content = `报错了,错误信息：${JSON.stringify(
              data
            )}。错误详情请到：https://cloud.baidu.com/doc/WENXINWORKSHOP/s/tlmyncueh 查看`;
            return [...msg];
          });
        }
      })
      .catch(function (error) {
        setMsgList((msg) => {
          msg[msg.length - 1].content = "对话出错了";
          return [...msg];
        });
        console.error(
          error,
          "对话出错了，参考下这个地址的错误类型：https://cloud.baidu.com/doc/WENXINWORKSHOP/s/tlmyncueh"
        );
      });
  };

  /**
   * 消息行渲染
   * @returns
   */
  const renderMsgLine = (item: TMsg) => {
    return (
      <div className="msgLine">
        <img
          src={item?.role === "user" ? head : reactIcon}
          alt="加载失败"
          className="head"
        />
        <div>{item?.content || "未能识别的消息"}</div>
      </div>
    );
  };

  /**
   * 发送消息
   */
  const handleSend = () => {
    let msgItem = {
      role: "user",
      content: sendValue,
    };
    sendInfoChat(msgItem);
    setMsgList((msg) => [
      ...msg,
      msgItem,
      {
        role: "assistant",
        content: "AI回复中...",
      },
    ]);
    setSendValue("");
  };

  useEffect(() => {
    getAccessToken();
  }, []);

  return (
    <>
      <header className="head">对话ai</header>
      <main className="window">
        {msgList.map((item) => renderMsgLine(item))}
      </main>
      {/* <Button onClick={sendInfoChat}>点击发送群聊请求</Button> */}
      <footer className="footer">
        <Input
          placeholder="请输入"
          className="input"
          value={sendValue}
          onChange={(e: any) => {
            setSendValue(e.target.value);
          }}
        />
        <Button onClick={handleSend} type="primary" className="sendBtn">
          发送
        </Button>
      </footer>
    </>
  );
}

export default App;
